// -----------------------------------------------------------------------
//  <copyright file="IdentityController.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-02-14 00:02</last-date>
// -----------------------------------------------------------------------

using Liuliu.Fsb.Services.Identity.Application.Identity.Users.Commands;
using Liuliu.Fsb.Services.Identity.Application.Identity.Users.Queries;


namespace Liuliu.Fsb.Services.Identity.Api.Controllers;

public class IdentityController(IMediator mediator) : Controller
{
    public IServiceProvider ServiceProvider => HttpContext.RequestServices;

    [HttpPost("/register")]
    [Produces<ApiResult>]
    public async Task<ActionResult> Register([FromBody] RegisterCommand command)
    {
        command.RegisterIp = HttpContext.GetClientIp();
        var result = await mediator.Send(command);
        return Ok(result);
    }

    [HttpGet("/login")]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View(new LoginCommand());
    }

    [HttpPost("/login")]
    public async Task<ActionResult> Login(LoginCommand command)
    {
        try
        {
            var loginResult = await mediator.Send(command);
            var user = loginResult.Data;
            loginResult.Data = null;

            if (!loginResult.IsSuccess())
            {
                if (user?.AccessFailedCount >= 2)
                {
                    ViewBag.NeedLoginCaptcha = true;
                }

                ModelState.AddModelError(string.Empty, loginResult.Message);
                return View(command);
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
            return View(command);
        }

        var returnUrl = command.ReturnUrl;
        if (string.IsNullOrEmpty(returnUrl))
        {
            returnUrl = "/";
        }

        return Redirect(returnUrl);
    }

    [HttpPost("/logout")]
    public async Task<ActionResult<ApiResult>> Logout()
    {
        var result = await mediator.Send(new LogoutCommand { Principal = User });
        return Ok(result);
    }

    [HttpGet("check-account/{account}")]
    public Task<bool> CheckAccount(string account)
    {
        var request = new CheckAccountExistsQuery { Account = account };
        return mediator.Send(request);
    }
}
